import {
    showHud
} from "../../electron-kit-hud/hud.js";
import {
    chManager,
    DelayType,
    SourceType,
    SumType
} from "./defaultconfig.js";
import { sendHiD, SendType } from "./send_manager.js";
let originChManager;
let originDefalutCh;
class DSPHandler {
    constructor() {
        this.receive_data = [];
        window.addEventListener('hid-receive-data', (event) => {
            const { data, reportid } = event.detail;
            if (data != null && data.length !== 0) {
                this.receive_data.push(Array.from(data));
            }
        });
    }

    ///custom模式下，自定义合频
    updateSum(out_ch, in_index) {
        if (chManager.current_sum != SumType.custom) return;
        if (out_ch.num < 1) return;
        const ch = chManager.chlist[out_ch.num - 1];
        ch.target_list[in_index] = ch.target_list[in_index] === 1 ? 0 : 1;
        sendHiD(SendType.SUM_CUSTOM, { ch: ch });
    }

    ///更新合频类型
    updateSUMType(sumtype) {
        chManager.current_sum = sumtype;
        switch (chManager.current_sum) {
            case SumType.ch2:
                chManager.chlist.forEach(($0, i) => {
                    $0.target_list.forEach((el, j) => {
                        const condition = (i % 2 === j) || (i === chManager.chlist.length - 2 && j === 0) || (i === chManager.chlist.length - 1 && j === 1)
                        $0.target_list[j] = condition ? 1 : 0;
                    });
                })
                sendHiD(SendType.SUM_2CH);
                break;
            case SumType.ch4:
                chManager.chlist.forEach(($0, i) => {
                    $0.target_list.forEach((el, j) => {
                        const condition = (i % 4 === j) || (i === chManager.chlist.length - 2 && j === 0) || (i === chManager.chlist.length - 1 && j === 1)
                        $0.target_list[j] = condition ? 1 : 0;
                    });
                })
                sendHiD(SendType.SUM_4CH);
                break;
            case SumType.ch6:
                chManager.chlist.forEach(($0, i) => {
                    $0.target_list.forEach((el, j) => {
                        const condition = (i % 6 === j) || (i === chManager.chlist.length - 2 && j === 0) || (i === chManager.chlist.length - 1 && j === 1)
                        $0.target_list[j] = condition ? 1 : 0;
                    });
                })
                sendHiD(SendType.SUM_6CH);
                break;
            case SumType.sum:
                chManager.chlist.forEach(($0, i) => {
                    $0.target_list.forEach((el, j) => {
                        const condition = (i % 2 === j % 2)
                        $0.target_list[j] = condition ? 1 : 0;
                    });
                })
                sendHiD(SendType.SUM_SUM);
                break;
            case SumType.custom:
                chManager.chlist.forEach(($0, i) => {
                    $0.target_list = Array.from({ length: chManager.chlist[0].target_list.length }, (_, i) => 0);
                    sendHiD(SendType.SUM_CUSTOM, { ch: $0 });
                });
                break;
            default:
                break;
        }

    }
    ///重置合频类型，默认重置到custom
    resetSUM() {
        this.updateSUMType(SumType.custom);
    }

    ///清除高电平的合频
    clearHilevelSum() {
        this.updateSUMType(SumType.custom);
    }

    ///清除BT | USB | AUX的合频
    clearBTSum() {
        chManager.chlist.forEach(($0, i) => {
            $0.target_list = Array.from({ length: chManager.chlist[0].target_list.length }, (_, i) => 0);
            sendHiD(SendType.SUM_USB_BT, { ch: $0 });
        });
    }

    // 默认光纤 ｜ 同轴的合频
    clearOpticalSum() {
        chManager.chlist.forEach(($0, i) => {
            $0.target_list = Array.from({ length: chManager.chlist[0].target_list.length }, (_, i) => 0);
            sendHiD(SendType.SUM_OPTICAL, { ch: $0 });
        });
    }

    ///默认高电平的合频
    defaultHilevelSum({ send = true } = {}) {
        chManager.current_sum = SumType.custom;
        chManager.chlist.forEach(($0, i) => {
            $0.target_list = Array.from({ length: chManager.chlist[0].target_list.length }, (_, i) => 0);
            $0.target_list[($0.num - 1) % 4] = 1;
            if (send === true) {
                sendHiD(SendType.SUM_CUSTOM, { ch: $0 });
            }
        });
    }
    ///默认BT | USB | AUX 的合频
    defaultBTSum({ send = true } = {}) {
        chManager.chlist.forEach(($0, i) => {
            $0.target_list = Array.from({ length: chManager.chlist[0].target_list.length }, (_, i) => 0);
            $0.target_list[($0.num + 1) % 2] = 1;
            if (send === true) {
                sendHiD(SendType.SUM_USB_BT, { ch: $0 });
            }
        });
    }
    // 默认光纤 ｜ 同轴的合频
    defaultOpticalSum({ send = true } = {}) {
        chManager.chlist.forEach(($0, i) => {
            $0.target_list = Array.from({ length: chManager.chlist[0].target_list.length }, (_, i) => 0);
            $0.target_list[($0.num + 1) % 2] = 1;
            if (send === true) {
                sendHiD(SendType.SUM_OPTICAL, { ch: $0 });
            }
        });
    }

    ///更换音源
    updateSource() {
        ///6进8出
        // chManager.current_source_list.forEach(($0) => sendHiD(SendType.SOURCE, { data: $0 }));
        ///12进12出
        // const data = chManager.current_source_list.map(($0, i) => [0xC1 + i, $0]).flat();
        // sendHiD(SendType.SOURCE, { data: data })
        chManager.current_source_list.forEach(($0, i) => sendHiD(SendType.SOURCE, { data: [0xC1 + i, $0] }));

        if (chManager.current_source_list.length > 0) {
            const last_source = chManager.current_source_list[chManager.current_source_list.length - 1];
            switch (last_source) {
                case SourceType.rca:

                    break;
                case SourceType.aux:
                case SourceType.bt:
                case SourceType.usb:
                case SourceType.optical:
                case SourceType.coaxial:
                    break;
                default:
                    break;
            }

        } else {

        }
    }

    ///重置通道eq
    resetEQ(resetAll, { send = true } = {}) {
        chManager.config.effectIndex = -1;
        const chlist = chManager.chlist;
        const list = resetAll ? chlist.concat(chManager.default_ch) : chManager.current_chlist;
        list.forEach(($0) => {
            $0.sign_list.forEach((sign) => { sign.reset() });
            ///板子清除EQ，并不会清除高低通
            // $0.high_pass.reset();
            // $0.low_pass.reset();
        });

        if (send === false) return;

        if (resetAll === true) {
            chManager.isbyPass = false;
            sendHiD(SendType.RESET_EQ);
        } else {
            if (chManager.current_chlist.length === 1 && chManager.current_chlist[0].num === 0) {
                return;
            }
            list.forEach(($0) => sendHiD(SendType.RESET_EQ, { ch: $0 }));
        }
    }

    ///更新增益
    updateGain(index, gain) {
        if (isNaN(gain)) return;
        chManager.current_chlist.forEach(($0) => {
            const sign = $0.sign_list[index];
            sign.gain = Math.min(Math.max(gain, sign.min_gain), sign.max_gain);
            sendHiD(SendType.EQ, { ch: $0, sign: sign });
        });
    }

    ///更新Q值
    updateQ(index, q) {
        if (isNaN(q)) return;
        chManager.current_chlist.forEach(($0) => {
            const sign = $0.sign_list[index];
            const q2 = Math.round(q * 10) / 10
            sign.q = Math.min(Math.max(q2, sign.min_q), sign.max_q);
            sendHiD(SendType.EQ, { ch: $0, sign: sign });
        });
    }

    ///更新频点的频率
    updateEQFreq(index, freq) {
        if (isNaN(freq)) return;
        chManager.current_chlist.forEach(($0) => {
            const sign = $0.sign_list[index];
            const f = Math.round(freq);
            sign.freq = Math.min(Math.max(f, sign.min_freq), sign.max_freq);
            sign.freq = f;
            sendHiD(SendType.EQ, { ch: $0, sign: sign });
        });
    }

    ///更新指定频点到全部参数
    updateEQ(gain, freq, q, index) {
        if (isNaN(gain) || isNaN(freq) || isNaN(q)) return;
        chManager.current_chlist.forEach(ch => {
            ch.sign_list[index].freq = Math.round(freq);
            ch.sign_list[index].gain = gain;
            ch.sign_list[index].q = q;
            sendHiD(SendType.EQ, { ch: ch, sign: ch.sign_list[index] });
        });
    }

    ///预设eq
    setPresentEQ(index) {
        chManager.config.effectIndex = index;
        const chlist = chManager.chlist;
        const list = chlist.concat(chManager.default_ch)
        list.forEach(($0) => $0.sign_list.forEach((sign, i) => {
            sign.reset();
            sign.gain = chManager.config.effectList[index][i];
            sendHiD(SendType.EQ, { ch: $0, sign: sign });
        }));
    }
    ///保存到设备
    setSaveToDevice(index) {
        chManager.config.presetIndex = index;
        sendHiD(SendType.SAVE_TO_MCU, { data: 0xD1 + parseInt(index) });
        showHud('Successfuly', 1000); // 显示3秒
    }

    ///调用设备保存的数据
    getDevicePreset(index, { completion = () => { } } = {}) {
        chManager.config.presetIndex = index;
        this.resetEQ(true, { send: false });
        sendHiD(SendType.GET_DATA_MCU, { data: 1 + parseInt(index) });
        if (completion != null) {
            completion();
        }
    }

    ///延迟类型切换，以毫秒为基准，获取对应类型的值
    getDelayValue(index) {
        const ch = chManager.chlist[index];
        let v = ch.delay;
        switch (chManager.delayType) {
            case DelayType.ms:
                v = Math.min(Math.max(v, 0), parseInt(ch.max_delay, 10));
                break;
            case DelayType.cm:
                v = v * 34.3;
                v = Math.min(Math.max(v, 0), parseInt(ch.max_delay * 34.3, 10));
                break;
            case DelayType.inch:
                v = v * 34.3 * 0.3937;
                v = Math.min(Math.max(v, 0), parseInt(ch.max_delay * 34.3 * 0.3937, 10));
                break;
            default:
                break;
        }
        return Math.round(v * 10) / 10;
    }

    ///延迟更新
    updateDelay(index, value) {
        if (index < 0 || index >= chManager.chlist.length) {
            return;
        }
        const ch = chManager.chlist[index];
        let v = value;
        switch (chManager.delayType) {
            case DelayType.ms:
                v = Math.min(Math.max(v, 0), parseInt(ch.max_delay, 10));
                break;
            case DelayType.cm:
                v = Math.min(Math.max(v, 0), parseInt(ch.max_delay * 34.3, 10));
                v = v / 34.3;
                v = (value * 10) % 343 === 0 ? parseInt(v, 10) : (v).toFixed(5);
                break;
            case DelayType.inch:
                v = Math.min(Math.max(v, 0), parseInt(ch.max_delay * 34.3 * 0.3937, 10));
                v = v / 34.3 / 0.3937;
                v = (value * 10000) % (343 * 3937) === 0 ? parseInt(v, 10) : (v).toFixed(5);
                break;
            default:
                break;
        }
        ch.delay = v;
        sendHiD(SendType.DELAY, { ch: ch });
    }

    ///更新高低通滤波类型
    updateSlopeType(ishigh, typeIndex, slope) {
        chManager.current_chlist.forEach((ch) => {
            const pass = ishigh ? ch.high_pass : ch.low_pass;
            pass.type_index = typeIndex;
            pass.type.slope = parseInt(slope, 10);
            sendHiD(ishigh ? SendType.PASS_HIGH : SendType.PASS_LOW, { ch: ch, pass: pass });
        });
    }

    ///更新高低通斜率
    updateSlope(ishigh, slope) {
        chManager.current_chlist.forEach((ch) => {
            const pass = ishigh ? ch.high_pass : ch.low_pass;
            pass.type.slope = parseInt(slope, 10);
            sendHiD(ishigh ? SendType.PASS_HIGH : SendType.PASS_LOW, { ch: ch, pass: pass });
        });
    }

    ///更新高低通
    updatePassFreq(ishigh, freq) {
        if (isNaN(freq)) return;
        chManager.current_chlist.forEach((ch) => {
            const pass = ishigh ? ch.high_pass : ch.low_pass;
            const value = parseInt(freq, 10);
            if (value >= pass.min_freq && value <= pass.max_freq) {
                pass.freq = value;
                sendHiD(ishigh ? SendType.PASS_HIGH : SendType.PASS_LOW, { ch: ch, pass: pass });
            }
        });
    }



    ///更新通道正反向. |||| 正反向不联调
    updatePhase(ch) {
        ch.phase = !ch.phase;
        if (ch.num < 1) return;
        sendHiD(SendType.PHASE, { ch: ch });
    }

    ///更新通道静音，音量
    updateDB(mute, dbvalue) {
        chManager.current_chlist.forEach((ch) => {
            const val = parseInt(dbvalue, 10);
            ch.mute = mute;
            ch.db = Math.min(Math.max(val, ch.min_db), ch.max_db);
            if (ch.num < 1) return;
            sendHiD(SendType.DB, { ch: ch });
        });
    }

    ///更新总音量
    updateAllDB(mute, dbvalue) {
        const val = parseInt(dbvalue, 10);
        chManager.mute = mute;
        chManager.db = Math.min(Math.max(val, chManager.min_db), chManager.max_db);
        sendHiD(SendType.DB_ALL);
    }

    ///通道直通/恢复均衡
    byPassorRestore() {
        if (!chManager.isbyPass) {
            originChManager = chManager.clone();
            originDefalutCh = chManager.default_ch.clone();
            chManager.reset();
            chManager.default_ch.reset();
            chManager.isbyPass = true;
        } else {
            chManager.mute = originChManager.mute;
            chManager.chlist = chManager.chlist.map((ch, i) => {
                ch = originChManager.chlist[i].clone();
                return ch;
            });
            chManager.isbyPass = false;
            chManager.default_ch.mute = originDefalutCh.mute;
            chManager.default_ch.phase = originDefalutCh.phase;
            chManager.default_ch.db = originDefalutCh.db;
            chManager.default_ch.delay = originDefalutCh.delay;
            chManager.default_ch.high_pass = originDefalutCh.high_pass.clone();
            chManager.default_ch.low_pass = originDefalutCh.low_pass.clone();
            chManager.default_ch.sign_list = originDefalutCh.sign_list.map((e) => e.clone());
        }
        sendHiD(chManager.isbyPass ? SendType.BYPASS : SendType.RESTORE);
    }

    ///选中group，统一两个ch的状态，和数据 ，并发送
    selectGroup(group_index) {
        chManager.group_list.forEach((e, i) => {
            chManager.group_list[i] = group_index === i ? !chManager.group_list[group_index] : false;
        })

        const state = this.unitGroup(group_index * 2);

        if (state === false) return;

        chManager.current_chlist.forEach((ch) => {
            sendHiD(SendType.DB, { ch: ch });
            sendHiD(SendType.PASS_HIGH, { ch: ch, pass: ch.high_pass });
            sendHiD(SendType.PASS_LOW, { ch: ch, pass: ch.low_pass });
            ch.sign_list.forEach((e) => sendHiD(SendType.EQ_UNIT, { ch: ch, sign: e }))
        });
    }

    ///统一group的两个ch数据
    unitGroup(ch_index) {
        if (ch_index < 0) return;
        //先全部取消选中
        chManager.chlist.forEach(($0) => $0.select = false);
        const ch = chManager.chlist[ch_index];
        const other_ch = chManager.chlist[ch_index % 2 === 0 ? ch_index + 1 : ch_index - 1];

        const group_index = ch_index % 2 === 0 ? ch_index / 2 : (ch_index - 1) / 2;
        const state = chManager.group_list[group_index];
        ch.select = true;
        other_ch.select = state;

        if (state) {
            other_ch.mute = ch.mute;
            // other_ch.phase = ch.phase;///正反向，不统一联调
            other_ch.db = ch.db;
            other_ch.high_pass.freq = ch.high_pass.freq;
            other_ch.high_pass.type_index = ch.high_pass.type_index;
            other_ch.high_pass.type.type = ch.high_pass.type.type;
            other_ch.high_pass.type.slope = ch.high_pass.type.slope;

            other_ch.low_pass.freq = ch.low_pass.freq;
            other_ch.low_pass.type_index = ch.low_pass.type_index;
            other_ch.low_pass.type.type = ch.low_pass.type.type;
            other_ch.low_pass.type.slope = ch.low_pass.type.slope;

            other_ch.sign_list.forEach((e, i) => {
                e.freq = ch.sign_list[i].freq;
                e.gain = ch.sign_list[i].gain;
                e.q = ch.sign_list[i].q;
            });
        }
        return state;
    }

    ///限幅器
    updateLimit(level, speed, release) {
        chManager.current_chlist.forEach((ch) => {
            ch.limit_level = parseInt(level, 10);
            ch.limit_speed = parseInt(speed, 10);
            ch.limit_release = parseInt(release, 10);
            sendHiD(SendType.LIMIT, { ch: ch });
        });
    }
    ///更新噪音
    updateNoise(noise) {
        chManager.noise = noise;
        sendHiD(SendType.NOISE);
    }

    ///获取设备的数据 0x00~0x01(分段),0x1~0xff(次数) 
    loadDevice(max_index, { index = 0, delay = 30, completion = () => { } } = {}) {
        if (max_index != null && index != null) {
            const current_num = Math.floor(parseInt(index) / 0xFF);
            //开始
            if (index === 0) {
                this.receive_data = [];
                showHud('Loading...', max_index * delay + 500); // 显示3秒
            }
            else if (index + 1 === max_index) {// 终止条件
                chManager.toModel(this.receive_data);
                completion();
                return;
            }
            // 发送当前请求
            ///12进12出这里做特殊处理，第一次读取90条。
            const send_index = chManager.chlist.length === 12 && index === 0 ? index % 0x5A + 1 : index % 0xFF + 1;
            sendHiD(SendType.LOAD_DEVICE, { data: { num: current_num, index: send_index } });
            // 计算下一次调用的参数
            const next_index = index + 1;
            // 延迟30ms后递归调用
            setTimeout(() => this.loadDevice(max_index, { index: next_index, delay, completion }), delay);
        } else {
            sendHiD(SendType.LOAD_DEVICE);
        }
    }


    ///全部发送到设备
    updateDevice(bytes, start, { delay = 30 } = {}) {
        if (bytes === null || bytes.length === 0 || bytes.length <= start) return;
        sendHiD(SendType.UPDATE, { data: bytes[start] });
        setTimeout(() => this.updateDevice(bytes, start + 1), delay);
    }

    ///保存文件
    async saveFile() {
        const bytes = chManager.toHex();
        console.log('================>>>>保存', bytes);
        const result = await window.FileAPI.saveFile({
            defaultFileName: 'my_data', // 默认文件名
            defaultFileExt: '.DSP',    // 默认扩展名
            // content: JSON.stringify({ name: content, age: 25 }) // 要保存的内容
            content: bytes
        });
        if (result.success) {
            console.log(`文件已保存到: ${result.path}`);
        } else {
            console.log(`保存失败: ${result.error}`);
        }
        return result;
    }

    //打开文件
    async openFile() {
        const result = await window.FileAPI.openFile();
        if (result.success) {
            console.log(`文件内容: ${result.content}`);
            const data = result.content.split('|\n').map((row) => row.split(',').map(($0) => parseInt($0, 16)));
            this.updateDevice(data, 0, { delay: 30 });
            const array = Array(chManager.config.startBytesIndex - 1).fill(0x00);
            const header = [0xAA,...array];
            const data_temp = data.map(($0) => [...header, ...$0]);
            // console.log('=============>. 222', data_temp);

            chManager.toModel(data_temp);
            showHud('同步数据中...', data.length * 30 + 500); // 显示3秒
            return data;
        } else {
            console.log(`打开失败: ${result.error}`);
            return null;
        }
    }

    async getChCustomName() {
        for (const ch of chManager.chlist) {
            const name = await window.saveAPI.getItem(ch.name);
            ch.custom_name = name || '';
        }
    }

    async setChCustomName(ch, value) {
        ch.custom_name = value;
        window.saveAPI.setItem(ch.name, value);
    }
}



const DSP = new DSPHandler()
export { DSP, DSPHandler };

